package com.dayuanit.dy15.atm.handler;

import com.dayuanit.dy15.atm.annotation.RequestMapping;
import com.dayuanit.dy15.atm.bean.BeanFactory;
import com.dayuanit.dy15.atm.bean.DefaultBeanFactory;
import com.dayuanit.dy15.atm.util.BeanFactoryUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class HanderMapping {
    //key=url  value=Controller  散列表 or 哈希表  底层是：数组+链表
    //链表解决的是对象的hash冲突问题，如果两个对象的hash值相等，就要看equals是否相等，
    //若equals相等，则覆盖；反之，则创建一个node节点追加到后面，形成一个链表。
    private static final Map<String, Object> urlControllerMap = new HashMap<>();

    static {
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object getController(String url) {
        return urlControllerMap.get(url);
    }

    public static void init() throws Exception {
        //创建对象，交给BeanFactory  做两件事情，1.创建对象 2.为对象赋上初始值 也就是Controller赋值service
        //IOC和DI 也就是创建对象和对象依赖关系 就是spring
        Map<String, Object> objects = BeanFactoryUtil.beanFactory.getObjects();


        //做URL映射  其实就是springMVC
        for (Map.Entry<String, Object> entry : objects.entrySet()) {
            Object obj = entry.getValue();
            Class clazz = obj.getClass();

            Method[] declaredMethods = clazz.getDeclaredMethods();
            for (Method method : declaredMethods) {
                Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
                for (Annotation annotation : declaredAnnotations) {
                    if (annotation.annotationType() == RequestMapping.class) {
                        RequestMapping requestMapping = (RequestMapping)annotation;
                        String url = requestMapping.value();
                        //k=url v=Controller对象
                        urlControllerMap.put(url, obj);
                    }
                }
            }
        }

        for (Map.Entry<String, Object> entry : urlControllerMap.entrySet()) {
            System.out.println("URL映射>>>>>>>" + entry.getKey() + ":" + entry.getValue());
        }

    }
}
